<script lang="ts" setup>
import { ref, reactive, watchEffect, watch, onBeforeUnmount } from 'vue'
import API from "@/service/api/login";
import rules from "@/utils/rule";
import { mStyles } from "@/utils/useStyles";
import { useStore } from "@/stores/user"
import { requestToast } from "@/utils/requestToast";
import { someFieldStore } from "@/stores/somefield";
import { getUrlParamValue } from "@/utils/getUrlParams";
import agreement from "./agreement.vue";
import privacy from "./privacy.vue";
import { useDynamicKeepAlive } from '@/utils/keepAliveUtils'
import { useFullPage } from "@/hook/useFullPage";
import { truncateText } from "@/utils/ellipsis";
import PhoneLogin from './plugin/PhoneLogin.vue';

// 登录参数
const mPhoneLoginParams = reactive({
    phone: "",
    sms_code: "",
});
const mAccountLoginParams = reactive({
    user_name: "",
    password: "",
});

// 协议
const mChecked = ref(0);

// 切换登录方式
const mTitle = ref("手机验证码登录");
const mAccount = ref(false);
const mChangeText = ref("账号密码登录");

const clkChangelogin = () => {
    mAccount.value = !mAccount.value;
    mTitle.value = mAccount.value ? "账号密码登录" : "手机验证码登录";
    mChangeText.value = mAccount.value ? "手机验证码登录" : "账号密码登录";
};

// 用户状态
const mStore = useStore();
const mSomefield = someFieldStore();
const mUserList = ref();
mUserList.value = mStore.userInf.user_list;

// 多个手机号登录
const mPhoneLogin = ref(false);

const { removeCachedView } = useDynamicKeepAlive()
const clkLogin = async (params: {}, api: string, type: string) => {
    const { data, status } = await requestToast(params, api, "登录成功")
    if (status) {
        // 清空本地存储的一些字段
        if (getUrlParamValue('access_token', mSomefield.clientfields) == null) {
            mSomefield.$reset();
        }
        // 清空工单页和首页缓存
        removeCachedView('', 'order');
        removeCachedView('', 'home');
        mSomefield.order_num = "";

        // 如果是手机登录并且有多个账号
        if (type == 'phone' && data.user_list.length >= 2) {
            mStore.updateUser(data, type);
            mUserList.value = mStore.userInf.user_list;
            mPhoneLogin.value = true;
        } else {
            mStore.updateUser(data, type);
        }
    }
};

const clkPhoneBeforeClose = (index: number) => {
    mStore.getToken(index);
}

// 登录
const mActionSheetRef = ref()
const mAgreement = ref(true);

// 手机验证码登录校验状态
const mIsValidPhoneLogin = ref(false)

const clkOnSubmit = async () => {
    if (mChecked.value == 1) {
        if (!mAccount.value) {
            clkLogin(mPhoneLoginParams, API.loginSms, 'phone');
        } else {
            clkLogin(mAccountLoginParams, API.loginUser, 'account');
        }
    } else {
        mActionSheetRef.value.openDialog()
    }
};

// 点击动作面板确认
const clkBeforeClose = () => {
    mActionSheetRef.value.closeDialog()
    mChecked.value = 1;
    clkOnSubmit();
}

// 点亮确认按钮
watchEffect(() => {
    if (!mAccount.value) {
        // 手机登录方式 → 取决于 PhoneLogin 返回的校验状态
        mAgreement.value = !mIsValidPhoneLogin.value;
    } else {
        // 账号密码登录方式
        const isUserNameValid = mAccountLoginParams.user_name.length > 0;
        const isPasswordValid = mAccountLoginParams.password.length > 0;
        mAgreement.value = !(isUserNameValid && isPasswordValid);
    }
});

// 打开协议
const mAgrMactionSheetRef = ref();
const mAgreementType = ref();
const clkOpenAgreement = (e: string) => {
    mAgreementType.value = e;
    mAgrMactionSheetRef.value.openDialog()
};

// 显示密码
const mShowPwd = ref('password');
let passwordIconTimer: ReturnType<typeof setTimeout> | null = null;
let passwordTimer: any = ref();
const passwordIcon = ref(false);

const handlePasswordFocus = () => {
    passwordIcon.value = true;
    if (passwordIconTimer) {
        clearTimeout(passwordIconTimer);
        passwordIconTimer = null;
    }
};
const handlePasswordBlur = () => {
    passwordIconTimer = setTimeout(() => {
        passwordIcon.value = false;
        passwordIconTimer = null;
    }, 3000);
};
watch(mShowPwd, (newValue) => {
    if (passwordTimer) {
        clearTimeout(passwordTimer);
        passwordTimer = null;
    }
    if (newValue === 'text') {
        passwordTimer = setTimeout(() => {
            mShowPwd.value = 'password';
            passwordTimer = null;
        }, 2000);
    }
});
onBeforeUnmount(() => {
    if (passwordIconTimer) {
        clearTimeout(passwordIconTimer);
    }
    if (passwordTimer) {
        clearTimeout(passwordTimer);
    }
});

const { pageRef } = useFullPage()

// 接收子组件校验状态
function handlePhoneValidation(isValid: boolean) {
    mIsValidPhoneLogin.value = isValid
}
</script>

<template>
    <div class="gr-bg" ref="pageRef">
        <cNavbar class="m-t-[5px]" iBgColor="#F6F6F6" :iFontColor="mStyles?.color2" leftArrow></cNavbar>
        <div class="gr-login" v-show="mPhoneLogin == false">
            <div>
                <h1 class="text-[48px] font-bold m-b-[55px]">{{ mTitle }}</h1>
                <cVanForm @Submit="clkOnSubmit">
                    <!-- 手机登录 -->
                    <PhoneLogin v-if='!mAccount' v-model="mPhoneLoginParams"
                        :api-config="{ sendCodeApi: API.smsCode, type: 'phone' }"
                        @validation-change="handlePhoneValidation" />
                    <!-- 账号密码登录 -->
                    <div class="gr-account" v-if='mAccount'>
                        <van-cell-group>
                            <cVanfield label="账号" placeholder="请输入账号" label-width="10vmin" :rules="rules.user_name"
                                v-model="mAccountLoginParams.user_name" clearable>
                            </cVanfield>
                        </van-cell-group>
                        <van-cell-group class="mt-[40px]">
                            <cVanfield label="密码" placeholder="请输入密码" label-width="10vmin" :rules="rules.password"
                                v-model="mAccountLoginParams.password" :type="mShowPwd" clearable
                                @blur="handlePasswordBlur" @focus="handlePasswordFocus">
                                <template #right-icon>
                                    <div class="flex" v-show="passwordIcon">
                                        <van-icon name="closed-eye" @click="mShowPwd = 'text'"
                                            v-show="mShowPwd === 'password'" />
                                        <van-icon name="eye-o" @click="mShowPwd = 'password'"
                                            v-show="mShowPwd === 'text'" />
                                    </div>
                                </template>
                            </cVanfield>
                        </van-cell-group>
                    </div>
                    <van-cell-group>
                        <cButton text="验证并登录" iLinearGradien :iColor="mStyles?.color10" class="w-[100%] mt-[35px]" round
                            iHeight="6vmin" iPadding="6vmin" native-type="submit" :disabled="mAgreement" />
                    </van-cell-group>
                </cVanForm>
                <van-cell-group>
                    <div class="gr-agr m-t-[31px] c-[#979797]">
                        <van-checkbox v-model="mChecked" icon-size="3.5vmin" class="m-r-[10px]"
                            :checked-color="mStyles?.color1"></van-checkbox>
                        <p class="text-[24px] text-[#3D3D3D]/60">
                            我已阅读并同意
                            <span class="text-[#4E7ABC]" @click="clkOpenAgreement('yonghu')">《用户协议》</span>
                            <span class="text-[#4E7ABC]" @click="clkOpenAgreement('yinsi')">《隐私协议》</span>
                        </p>
                    </div>
                </van-cell-group>
            </div>
            <div class="text-center w-[100%]" v-show="mPhoneLogin == false">
                <span class="text-[#FF0000] text-[28px] font-medium" @click="clkChangelogin">
                    {{ mChangeText }}</span>
            </div>
        </div>

        <!-- 协议弹窗 -->
        <cVanActionSheet ref="mActionSheetRef" @is-Confirm="clkBeforeClose" iClose :iButton="false"
            iPadding="6.25vmin 3.125vmin 8.854vmin 3.125vmin" iCloseIconTop="6.8vmin">
            <h1 class="font-bold text-[34px]">服务协议与隐私保护</h1>
            <p class="text-[#3D3D3D]/60 text-[24px] text-left p-t-[40px]">
                <span class="m-l-[10px]">登录前，请先阅读并同意</span>
                <span class="text-[#4E7ABC]" @click="clkOpenAgreement('yonghu')">《用户协议》</span>
                <span class="text-[#4E7ABC]" @click="clkOpenAgreement('yinsi')">《隐私协议》</span>
            </p>
            <cButton class="w-[100%] m-t-[40px] text-[28px] font-medium" iLinearGradien round iColor="white"
                iHeight="9.6vmin" @click="clkBeforeClose">同意并继续</cButton>
        </cVanActionSheet>

        <!-- 多账号选择 -->
        <div class="gr-phone-login" v-show="mPhoneLogin == true">
            <h1 class="text-[48px] font-bold p-l-[20px] p-r-[20px] m-b-[8px]">请选择要登录的账号</h1>
            <h2 class="text-[24px] font-350 color-[#3D3D3D]/60 m-b-[65px] p-l-[20px] p-r-[20px]">您的手机号已绑定以下账号，请选择账号登录
            </h2>
            <van-badge class="w-[100%]">
                <div v-for="(item, index) in mUserList" class="gr-user-list">
                    <span class="text-[32px] font-medium" v-if="item.nick_name != ''">{{ truncateText(item.nick_name,
                        12)
                        }}</span>
                    <span class="text-[32px] font-medium" v-else>{{ truncateText(item.user_name, 12) }}</span>
                    <cButton iLinearGradien :iColor="mStyles?.color10" class="w-[128px] contents" iHeight="6.722vmin"
                        round @click="clkPhoneBeforeClose(index)">登录</cButton>
                </div>
            </van-badge>
        </div>

        <cVanActionSheet ref="mAgrMactionSheetRef" :iButton="false" iPadding="2vmin" iTextAlign="inherit">
            <agreement v-if="mAgreementType == 'yonghu'"></agreement>
            <privacy v-if="mAgreementType == 'yinsi'"></privacy>
        </cVanActionSheet>
    </div>
</template>

<style lang="scss" scoped>
:deep(.van-action-sheet__content) {
    overflow: hidden;
}

.gr-bg {
    background: #F6F6F6;

    .gr-login {
        width: 590px;
        margin: 15px auto;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        min-height: calc(100vh - 16.146vh - 6.641vh);

        :deep(.van-field) {
            font-size: 32px;
            font-weight: 500;
            border-bottom: 1px solid rgba(61, 61, 61, 0.10);
            padding-left: 0;
            background: #F6F6F6;
        }
    }
}

.van-hairline--top-bottom:after {
    display: none;
}

.gr-phone-login {
    margin: 20px 48px 20px 48px;
}

.gr-agr {
    display: flex;
    align-items: center;
    margin-left: 15px;
}

.gr-user-list {
    height: 114px;
    display: flex;
    justify-content: space-between;
    background: rgba(61, 61, 61, 0.03);
    border-radius: 23px;
    margin-bottom: 10px;
    align-items: center;
    padding-left: 32px;
    padding-right: 32px;
}

:deep(.van-cell-group) {
    background: #F6F6F6;
}
</style>
